package com.example.cores_middle_activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.cores_middle_activity.Utils.ViewUtil;

import java.util.Random;

public class Login_main extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {

    private String PASSWORD = "123456";
    private String smsCode = "";
    private RadioGroup rgLoginMethods;
    private EditText etPhoneNumber;
    private EditText etPassword;
    private TextView tvPassword;
    private Button btnForgetPassword;
    private CheckBox cbRemember;
    private Button btnLogin;
    private RadioButton rbSmsCode;
    private RadioButton rbPassword;
    private ActivityResultLauncher<Intent> register;
    private SharedPreferences.Editor edit;
    private SharedPreferences preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_login_main);

        rgLoginMethods = findViewById(R.id.rg_login);
        rbPassword = findViewById(R.id.rb_password);
        rbSmsCode = findViewById(R.id.rb_verify_code);
        etPhoneNumber = findViewById(R.id.et_phone_number);
        etPassword = findViewById(R.id.et_password);
        tvPassword = findViewById(R.id.tv_password);
        btnForgetPassword = findViewById(R.id.btn_forget_password);
        cbRemember = findViewById(R.id.cb_remember);
        btnLogin = findViewById(R.id.btn_login);

        // 切换登录方式
        rgLoginMethods.setOnCheckedChangeListener(this);
        // 手机号输入验证
        etPhoneNumber.addTextChangedListener(new HideTextWatcher(etPhoneNumber, 11));
        // 短信验证码输入验证
        etPassword.addTextChangedListener(new HideTextWatcher(etPhoneNumber, 6));
        // 获取验证码、忘记密码
        btnForgetPassword.setOnClickListener(this);

        // 登录
        btnLogin.setOnClickListener(this);

        // 找回密码页面返回
        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult o) {

            }
        });

        // 如果是记住密码，则读取本地保存的账号密码
        preferences = getSharedPreferences("user", Context.MODE_PRIVATE);
        edit = getSharedPreferences("user", Context.MODE_PRIVATE).edit();
        rememberMe();

    }

    // 切换登录方式
    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int id) {
        // 密码登录
        if (R.id.rb_password == id) {
            setLoginWithPassword();
        } else if (R.id.rb_verify_code == id) {
            // 验证码登录
            setLoginWithSMS();
        }
    }

    private void setLoginWithPassword() {
        tvPassword.setText(R.string.password);
        btnForgetPassword.setText(R.string.forget_password);
        etPassword.setHint(R.string.please_enter_password);
        cbRemember.setVisibility(View.VISIBLE);
    }

    private void setLoginWithSMS() {
        tvPassword.setText(R.string.verify_code);
        btnForgetPassword.setText(R.string.get_verify_code);
        etPassword.setHint(R.string.please_enter_verify_code);
        cbRemember.setVisibility(View.GONE);
    }

    // 忘记密码、
    private void handleForgetPassowrd() {
        String phoneNumber = etPhoneNumber.getText().toString();
        // 跳转找回密码页面
        Intent intent = new Intent(this, RetrievePassword.class);
        intent.putExtra("phoneNumber", phoneNumber);
        register.launch(intent);
    }

    // 获取短信验证码
    private void handleGetSmsCode() {
        String phoneNumber = etPhoneNumber.getText().toString();
        // 生产6位数验证码
        smsCode = String.format("%06d", new Random().nextInt(9999));
        // 提示显示验证码
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("验证码");
        String msg = String.format("用户：%s\n验证码是：%s", phoneNumber, smsCode);
        builder.setMessage(msg);
        builder.setPositiveButton("我记住了", null);
        builder.create().show();
    }

    // 记住密码
    private void saveUser() {
        String phoneNumber = etPhoneNumber.getText().toString();
        String password = etPassword.getText().toString();


        edit.putString("phoneNumber", phoneNumber);
        edit.putString("password", password);

        edit.commit();
    }

    // 读取账号密码
    private void rememberMe() {
        String phoneNumber = preferences.getString("phoneNumber", null);
        if (phoneNumber != null) {
            etPhoneNumber.setText(phoneNumber);
        }

        String password = preferences.getString("password", null);
        if (password != null) {
            etPassword.setText(password);
        }

    }

    // 密码登录
    private void handleLoginWithPassword() {
        boolean validation = PASSWORD.equals(etPassword.getText().toString());
        if (!validation) {
            Toast.makeText(this, "密码错误", Toast.LENGTH_LONG).show();
        }
        // 密码正确
        Toast.makeText(this, "登录成功", Toast.LENGTH_LONG).show();

        if (cbRemember.isChecked()) {
            saveUser();
        }

    }

    // 短信验证码登录
    private void handleLoginWithSmsCode() {
        if ("".equals(smsCode)) {
            Toast.makeText(this, "请先获取验证码", Toast.LENGTH_LONG).show();
            return;
        }

        boolean validation = smsCode.equals(etPassword.getText().toString());
        if (!validation) {
            Toast.makeText(this, "验证码错误", Toast.LENGTH_LONG).show();
            return;
        }

        // 登陆成功
        Toast.makeText(this, "登录成功", Toast.LENGTH_LONG).show();
    }


    @Override
    public void onClick(View view) {
        // 手机号长度不满11位提示
        if (etPhoneNumber.getText().length() < 11) {
            Toast.makeText(this, "手机号格式错误", Toast.LENGTH_LONG).show();
            return;
        }

        int id = view.getId();
        boolean isLoginEvent = R.id.btn_login == id;
        boolean ohterEvent = R.id.btn_forget_password == id;

        boolean isLoginByPassword = rbPassword.isChecked() == true;
        boolean isLoginBySmsCode = rbSmsCode.isChecked() == true;

        boolean isGetSmsCodeEvent = ohterEvent && isLoginBySmsCode;
        boolean isForgetPasswordEvent = ohterEvent && isLoginByPassword;
        boolean isLoginWithPasswordEvent = isLoginByPassword && isLoginEvent;
        boolean isLoginWithSmsCodeEvent = isLoginBySmsCode && isLoginEvent;

        if (isForgetPasswordEvent) {
            handleForgetPassowrd();
        } else if (isGetSmsCodeEvent) {
            handleGetSmsCode();
        } else if (isLoginWithPasswordEvent) {
            handleLoginWithPassword();
        } else if (isLoginWithSmsCodeEvent) {
            handleLoginWithSmsCode();
        }
    }


    private class HideTextWatcher implements TextWatcher {
        EditText editText;
        int length;

        public HideTextWatcher(EditText editText, int length) {
            this.editText = editText;
            this.length = length;
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            Log.d("zhoutao", "input ");
            if (editable.length() >= length) {
                ViewUtil.hideOneInputMethod(Login_main.this, editText);
            }
        }
    }
}